<template>
  <section class="todoapp">
    <todo-header @add="handleAdd"></todo-header>
    <TodoMain :list="list2" @del="handleDel" @state="handleState"></TodoMain>
    <todo-footer
      :list="list"
      @delCompleted="handleClear"
      :flag="flag"
      @changeFlag="
        (val) => {
          flag = val
        }
      "
    ></todo-footer>
  </section>
</template>

<script>
import TodoHeader from '@/components/TodoHeader.vue'
import TodoMain from '@/components/TodoMain.vue'
import TodoFooter from '@/components/TodoFooter.vue'
export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      // list: [
      //   { id: 12, name: '吃饭', isDone: false },
      //   { id: 14, name: '听歌', isDone: true },
      //   { id: 23, name: '洗澡', isDone: true },
      //   { id: 34, name: '睡觉', isDone: false },
      //   { id: 35, name: '游戏', isDone: false },
      // ],
      list: JSON.parse(localStorage.getItem('todolist')) || [],
      flag: 1,
    }
  },
  methods: {
    handleAdd(todoname) {
      // console.log(todoname)
      // 向数组中添加元素：push、unshift
      this.list.unshift({
        id: +new Date(),
        name: todoname,
        isDone: false,
      })
    },
    deldel(id) {
      this.list = this.list((item) => item.id !== id)
    },
    handleState(id) {
      let res = this.list.find((item) => item.id == id)
      res.isDone = !res.isDone
    },
    handleClear() {
      //清楚已完成,保留未完成的,保留isDone=false的
      this.list = this.list.filter((item) => item.isDone === false)
    },
  },
  computed: {
    list2() {
      if (this.flag === '1') {
        return this.list
      } else if (this.flag === '2') {
        return this.list.filter((item) => item.isDone === false)
      } else {
        return this.list.filter((item) => item.isDone)
      }
    },
  },
  watch: {
    list: {
      deep: true,
      handler: function (newValue) {
        // newValue 就是更新后的结果
        localStorage.setItem('todolist', JSON.stringify(newValue))
      },
    },
  },
}
</script>

<style></style>
